package org.geektimes.rest.demo;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

public class RestClientPostDemo {

    public static void main(String[] args) {
        //无请求参数,返回文本
        test1();
        //有请求参数,返回文本
        test2();
        //无请求参数,返回JSON
        test3();
        //有请求参数,返回JSON
        test4();
    }

    private static void test1() {
        Client client = ClientBuilder.newClient();
        Response response = client
                .target("http://127.0.0.1:8080/a/b")
                .request()
                .post(null);

        String content = response.readEntity(String.class);
        System.out.println("无请求参数，返回结果:" + content);
    }

    private static void test2() {
        Client client = ClientBuilder.newClient();
        Response response = client
                .target("http://127.0.0.1:8080/a/c")
                .request()
                .property("test", "test")
                .post(null);

        String content = response.readEntity(String.class);
        System.out.println("有请求参数，返回结果:" + content);
    }

    private static void test3(){
        Client client = ClientBuilder.newClient();
        Response response = client
                .target("http://127.0.0.1:8080/a/d")
                .request()
                .property("test", "test")
                .post(null);

        User user = response.readEntity(User.class);
        System.out.println("有请求参数，返回JSON结果:" + user);
    }

    private static void test4(){
        User user = new User();
        user.setName("tom2");
        user.setAge(322);
        user.setTest("test2");

        Client client = ClientBuilder.newClient();
        Response response = client
                .target("http://127.0.0.1:8080/a/e")
                .request()
                .post(Entity.entity(user, MediaType.APPLICATION_JSON_TYPE));

        user = response.readEntity(User.class);
        System.out.println("有请求参数(JSON)，返回JSON结果:" + user);
    }

    public static class User{
        private String name;
        private Integer age;
        private String test;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public String getTest() {
            return test;
        }

        public void setTest(String test) {
            this.test = test;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", test='" + test + '\'' +
                    '}';
        }
    }
}
